import 'dart:ui';

import 'package:expandable_text/expandable_text.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:largefriends/config/lf_type_config.dart';
import 'package:largefriends/res.dart';
import 'package:largefriends/res/lf_double_ext.dart';
import 'package:largefriends/res/lf_fonts.dart';
import 'package:largefriends/res/lf_string_ext.dart';
import 'package:largefriends/res/lf_text_style.dart';
import 'package:largefriends/res/strings/lf_strings.dart';
import 'package:largefriends/service/lf_auth_service.dart';
import 'package:largefriends/widgets/custom_cache_image.dart';
import 'package:scroll_to_index/scroll_to_index.dart';

import '../../entity/entities/lf_photo_entity.dart';
import '../../entity/entities/lf_user_entity.dart';
import '../../net/lf_api_util.dart';
import '../../res/lf_color.dart';
import '../../res/lf_widget_ext.dart';
import '../../utils/lf_scroll_behavior.dart';
import '../../widgets/dialog_action_sheet.dart';
import '../../widgets/lf_button.dart';

class LfProfileWidget extends StatefulWidget {
  final LfUserEntity userEntity;
  final Function moreCall;
  const LfProfileWidget({Key? key, required this.userEntity, required this.moreCall}) : super(key: key);

  @override
  State<LfProfileWidget> createState() => _LfProfileWidgetState();
}

class _LfProfileWidgetState extends State<LfProfileWidget> {
  PageController pageController = PageController();
  AutoScrollController scrollController =
      AutoScrollController(axis: Axis.horizontal);
  RxInt photoIndex = 0.obs;
  @override
  Widget build(BuildContext context) {
    return ScrollConfiguration(
        behavior: LfScrollBehavior(),
        child: CustomScrollView(
          slivers: _items(),
        ));
  }

  List<Widget> _items() {
    List<Widget> items = List.empty(growable: true);
    items.add(_photoPager());
    items.add(_baseInfo().sliverBox);
    items.add(_textContent(
            title: 'Headline', content: widget.userEntity.headline ?? "")
        .sliverBox);
    items.add(
        _textContent(title: 'About Me', content: widget.userEntity.about ?? "")
            .sliverBox);
    items.add(_textContent(
            title: 'About My Match', content: widget.userEntity.about ?? "")
        .sliverBox);
    items.add(_basicInfo().sliverBox);
    items.add(120.h.sliverBox);
    return items;
  }

  Widget _photoPager() {
    List<LfPhotoEntity> photos = List.empty(growable: true);
    photos.addAll(widget.userEntity.publicPhotos());
    if (widget.userEntity.privateAlbumCnt > 0 &&
        widget.userEntity.privatePhotos().isEmpty) {
      for (var index = 0; index < widget.userEntity.privateAlbumCnt; index++) {
        photos.add(LfPhotoEntity(
            type: photoTypePrivate, url: Res.default_private_blur));
      }
    } else {
      photos.addAll(widget.userEntity.privatePhotos());
    }
    return SliverAppBar(
      leading: Center(
        child: InkWell(
          child: Container(
            padding: EdgeInsets.all(6.r),
            decoration: BoxDecoration(color: color210215, shape: BoxShape.circle),
            child: const Icon(
              Icons.close,
              color: Colors.white,
            ),
          ),
          onTap: (){
            Get.back();
          },
        ),
      ),
      expandedHeight: ScreenUtil().screenWidth * 1.3,
      pinned: true,
      actions: widget.userEntity.isSelf()?null: [
        IconButton(onPressed: () {
          widget.moreCall.call();
        }, icon: const Icon(Icons.more_horiz))
      ],
      flexibleSpace: FlexibleSpaceBar(
        collapseMode: CollapseMode.none,
        background: SizedBox(
          width: ScreenUtil().screenWidth,
          height: ScreenUtil().screenWidth * 1.3,
          child: photos.isEmpty
              ? const CustomCacheImage(
                  imageUrl: '',
                )
              : Stack(
                  children: [
                    Positioned.fill(
                        child: PageView.builder(
                      itemBuilder: (context, index) {
                        var photo = photos[index];
                        var image = CustomCacheImage(
                          imageUrl: photo.url,
                          width: ScreenUtil().screenWidth,
                          height: ScreenUtil().screenWidth * 1.3,
                        );
                        if (isSelf()) {
                          return image;
                        }
                        if (photo.type == photoTypePublic) {
                          return image;
                        }
                        var state = widget.userEntity.privateAlbumStatus;
                        var icon = const Icon(Icons.lock_outline);
                        var btn = empty;
                        if (state == 1) {
                          icon = const Icon(
                            Icons.lock_open,
                            color: Colors.white,
                          );
                        } else if (state == 2) {
                          icon = Icon(
                            Icons.lock_outline,
                            color: colorFF007F,
                          );
                          btn = SizedBox(
                            height: 50.h,
                            width: ScreenUtil().screenWidth - 60,
                            child: LfButton(
                                enabled: false,
                                text: "REQUESTED",
                                onPress: () {}),
                          );
                        } else {
                          icon = Icon(
                            Icons.lock_outline,
                            color: colorFF007F,
                          );
                          btn = SizedBox(
                            height: 50.h,
                            width: ScreenUtil().screenWidth - 60,
                            child: LfButton(
                                enabled: true,
                                text: "REQUEST",
                                onPress: () {
                                  requestPrivatePhoto(widget.userEntity);
                                }),
                          );
                        }
                        return Stack(
                          children: [
                            Positioned.fill(child: image),
                            Center(
                              child: Padding(
                                padding: EdgeInsets.only(bottom: 60.h),
                                child: btn,
                              ),
                            ),
                            Positioned(
                              right: 10.w,
                              bottom: 70.h,
                              child: icon,
                            )
                          ],
                        );
                      },
                      controller: pageController,
                      onPageChanged: (value) {
                        scrollController.scrollToIndex(value,
                            preferPosition: AutoScrollPosition.end);
                        photoIndex.value = value;
                      },
                      itemCount: photos.length,
                    )),
                    Align(
                      alignment: Alignment.bottomLeft,
                      child: IntrinsicHeight(
                        child: ClipRRect(
                          child: BackdropFilter(
                            filter: ImageFilter.blur(sigmaX: 10, sigmaY: 10),
                            child: Container(
                              height: 60.h,
                              width: ScreenUtil().screenWidth,
                              padding: EdgeInsets.symmetric(vertical: 5.h),
                              child: ListView.separated(
                                itemBuilder: (context, index) {
                                  return AutoScrollTag(
                                    key: ValueKey(
                                        'profile_${widget.userEntity.userId}_$index'),
                                    controller: scrollController,
                                    index: index,
                                    child: Obx(
                                      () => Container(
                                        margin: EdgeInsets.only(left: 6.w),
                                        decoration: BoxDecoration(
                                            borderRadius: 5.r.radius,
                                            border: Border.all(
                                                color: photoIndex.value == index
                                                    ? colorFF007F
                                                    : colorFEFEFE,
                                                width: 2.r)),
                                        child: InkWell(
                                          child: CustomCacheImage(
                                            imageUrl: photos[index].url,
                                            width: 50.h,
                                            height: 50.h,
                                            radius: 4.r,
                                          ),
                                          onTap: () {
                                            pageController.jumpToPage(index);
                                          },
                                        ),
                                      ),
                                    ),
                                  );
                                },
                                controller: scrollController,
                                scrollDirection: Axis.horizontal,
                                itemCount: photos.length,
                                separatorBuilder:
                                    (BuildContext context, int index) {
                                  return empty;
                                },
                              ),
                            ),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
        ),
      ),
    );
  }

  Widget _baseInfo() {
    return Container(
      padding:
          EdgeInsets.only(bottom: 16.h, left: 16.w, right: 10.w, top: 20.h),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Flexible(
                child: Text(
                  widget.userEntity.getNameWithGenderAge(),
                  style: lfTextStyle(sp: 16.sp, fontFamily: fontBold),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
              ),
              widget.userEntity.isVerified()?Padding(padding: EdgeInsets.only(left: 5.w),child: Image.asset(
                  widget.userEntity.isVerified()
                      ? Res.ic_verified
                      : Res.ic_verified_no,
                  width: 16.r),):empty,
              5.w.sbw,
              Image.asset(
                Res.icon_premium,
                width: 18.r,
                color: widget.userEntity.isGold()
                    ? colorFF007F
                    : Colors.transparent,
              ),
            ],
          ),
          5.h.sbh,
          widget.userEntity.getLiveIn().trim().isNotEmpty?Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Padding(
                padding: EdgeInsets.only(top: 2.h, right: 5.w),
                child: Icon(Icons.location_on_outlined,
                    size: 16.r, color: colorFF007F),
              ),
              Expanded(
                child: Text(
                  widget.userEntity.getLiveIn(),
                  style: lfTextStyle(
                      sp: 14.sp, fontFamily: fontRegular, color: colorFEFEFE),
                ),
              )
            ],
          ):empty,
        ],
      ),
    );
  }

  Widget _textContent({required String title, required String content}) {
    if ((content.trim().replaceBreak ?? "").isEmpty) {
      return empty;
    }
    return Container(
      margin: EdgeInsets.only(bottom: 16.h, left: 16.w, right: 10.w),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            title,
            style: lfTextStyle(sp: 16.sp, fontFamily: fontBold,color: color514F62),
          ),
          5.h.sbh,
          ExpandableText(
            content.trim().replaceBreak?.replaceWord(isSelf()) ?? "",
            expandText: '${strMore.tr}>>',
            collapseText: '<<${strLess.tr}',
            expandOnTextTap: false,
            animation: true,
            collapseOnTextTap: false,
            linkColor: colorFEFEFE,
            linkStyle: lfTextStyle(
                sp: 16.sp, fontFamily: fontMedium, color: colorFEFEFE),
            linkEllipsis: false,
            maxLines: 8,
            expanded: false,
            style: lfTextStyle(
                sp: 16.sp, fontFamily: fontRegular, color: colorFEFEFE),
          )
        ],
      ),
    );
  }

  Widget _basicInfo() {
    List<Widget> items = List.empty(growable: true);

    _detailItem(
        title: strHeight.tr,
        value: TypeConfig()
            .getValueByKey(LfConfigTypeEnum.height, widget.userEntity.height),
        items: items);
    _detailItem(
        title: strBodyType.tr,
        value: TypeConfig()
            .getValueByKey(LfConfigTypeEnum.body, widget.userEntity.body),
        items: items);
    _detailItem(
        title: strEthnicity.tr,
        value: TypeConfig().getValueByKey(
            LfConfigTypeEnum.ethnicity, widget.userEntity.ethnicity),
        items: items);
    _detailItem(
        title: strReligion.tr,
        value: TypeConfig().getValueByKey(
            LfConfigTypeEnum.religion, widget.userEntity.religion),
        items: items);
    _detailItem(
        title: strLanguages.tr,
        value: TypeConfig().getValueByKey(
            LfConfigTypeEnum.language, widget.userEntity.language),
        items: items);
    _detailItem(
        title: strEducation.tr,
        value: TypeConfig().getValueByKey(
            LfConfigTypeEnum.education, widget.userEntity.education),
        items: items);
    _detailItem(
        title: strOccupation.tr,
        value: TypeConfig().getValueByKey(
            LfConfigTypeEnum.occupation, widget.userEntity.occupation),
        items: items);
    _detailItem(
        title: strSmoking.tr,
        value: TypeConfig()
            .getValueByKey(LfConfigTypeEnum.smoke, widget.userEntity.smoke),
        items: items);
    _detailItem(
        title: strDrinking.tr,
        value: TypeConfig()
            .getValueByKey(LfConfigTypeEnum.drink, widget.userEntity.drink),
        items: items);
    _detailItem(
        title: strChildren.tr,
        value: TypeConfig().getValueByKey(
            LfConfigTypeEnum.haveChildren, widget.userEntity.haveChildren),
        items: items);
    _detailItem(
        title: strPets.tr,
        value: TypeConfig()
            .getValueByKey(LfConfigTypeEnum.pet, widget.userEntity.pet),
        items: items);
    if (items.isEmpty) {
      return empty;
    }

    return Container(
      margin: EdgeInsets.only(bottom: 20.h, left: 16.w, right: 16.w),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            strPersonalDetails.tr,
            style: lfTextStyle(
              sp: 16.sp,
              fontFamily: fontBold,
              color: color514F62
            ),
          ),
          5.h.sbh,
          ...items
        ],
      ),
    );
  }

  _detailItem(
      {required String title,
      required String value,
      required List<Widget> items}) {
    if (value.trim().isEmpty) {
      return;
    }
    var child = Padding(
      padding: EdgeInsets.only(top: 10.h),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            title,
            style: lfTextStyle(
                sp: 16.sp, fontFamily: fontRegular, color: color514F62),
          ),
          40.w.sbw,
          Expanded(
            child: Text(
              value,
              style: lfTextStyle(
                  sp: 16.sp, fontFamily: fontRegular, color: colorFEFEFE),
              textAlign: TextAlign.end,
            ),
          )
        ],
      ),
    );
    items.add(child);
  }

  LfAuthService authService = Get.find();
  bool isSelf() {
    return widget.userEntity.userId == authService.currentAccount!.userId;
  }
}
